<template>
	<el-dialog :title="isEdit ? '编辑字段' : '添加字段'" :visible="visible" width="50%" :before-close="handleClose" class="summary-create-container">
		<el-form ref="form" :model="form" :rules="rules">
			<el-form-item label="字段名称" prop="name">
				<el-input v-model="form.name" placeholder="请输入字段名称" maxLength="20" />
			</el-form-item>
			<el-form-item label="字段类型" prop="type" required>
				<el-select v-model="form.type" placeholder="请选择字段类型" :disabled="isEdit">
					<el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<div v-if="form.type !== 'input' && form.type !== 'textarea'">
				<el-form-item v-for="(item, index) in form.options" :key="index" :label="`选项${index + 1}`" :prop="'options.' + index + '.label'" :rules="rules.options" label-width="80px">
					<el-input v-model="item.label" placeholder="请输入选项" maxlength="20"> </el-input>
					<el-button type="primary" size="mini" icon="el-icon-minus" circle class="minus-button" @click="onRemove(index)" v-if="index !== 0"></el-button>
				</el-form-item>
			</div>

			<el-button
				v-if="form.type !== 'input' && form.type !== 'textarea' && this.form.options.length < 10"
				type="primary"
				size="mini"
				icon="el-icon-plus"
				circle
				class="plus-button"
				@click="onAdd()"
			></el-button>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="handleClose"> 取消 </el-button>
			<el-button type="primary" @click="submitForm"> 保存 </el-button>
		</span>
	</el-dialog>
</template>

<script>
import { addSessionSummary, updateSessionSummary } from '@/api/api';

export default {
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		data: {
			type: Object,
			default: () => {
				return {
					id: 0,
					name: '',
					type: 'input',
					options: [
						{
							label: '', // `选项1`,
							value: 1
						}
					],
					isRequired: 'Y'
				};
			}
		},
		summaryList: {
			type: Array,
			default: () => {
				return [];
			}
		}
	},
	data() {
		return {
			isEdit: false,
			form: {
				id: 0,
				name: '',
				type: 'input',
				options: [
					{
						label: '', // `选项1`,
						value: 1
					}
				],
				isRequired: 'Y'
			},
			// 单行文本；字段类型支持单选、多选、下拉单选、单行文本、多行文本
			typeOptions: [
				{
					label: '多选',
					value: 'checkbox'
				},
				{
					label: '单选',
					value: 'radio'
				},
				{
					label: '下拉单选',
					value: 'select'
				},
				{
					label: '单行文本',
					value: 'input'
				},
				{
					label: '多行文本',
					value: 'textarea'
				}
			],
			rules: {
				name: [
					{
						required: true,
						message: '请输入字段名称',
						trigger: 'blur'
					},
					{
						min: 1,
						max: 20,
						message: '字符长度限制20个汉字',
						trigger: 'blur'
					}
				],
				options: [
					{
						required: true,
						message: '请输入选项',
						trigger: 'blur'
					},
					{
						min: 1,
						max: 20,
						message: '字符长度限制20个汉字',
						trigger: 'blur'
					},
					{ validator: this.checkDuplicates, trigger: 'blur' }
				]
			}
		};
	},
	mounted() {
		console.log('this.data', this.data);
		console.log('this.$route.params', this.$route.params);

		if (this.data) {
			this.isEdit = true;
			const { id, name, type, data, isRequired } = this.data;
			this.form = { ...this.form, ...this.data };
			if (data?.options) {
				this.form.options = data.options.map((item, index) => {
					return {
						label: item,
						value: index + 1
					};
				});
			}
		}
	},
	methods: {
		handleClose() {
			this.$emit('close');
		},
		submitForm() {
			this.$refs['form'].validate(valid => {
				if (valid) {
					const { id, type, name, options, isRequired } = this.form;
					if (!name.trim()) {
						this.$message({
							message: '字段名称不能为空',
							type: 'error'
						});
						return false;
					}
					if (this.summaryList.some(item => item.name === name.trim() && item.id !== id)) {
						this.$message({
							message: '字段名称不能重复',
							type: 'error'
						});
						return false;
					}
					let data = {};
					if (type === 'input' || type === 'textarea') {
						// {"name": "字段名称","type": "single-line-text","data": {},"isRequired": "Y"}
						data = {
							name: name.trim(),
							type: type,
							data: {},
							isRequired: isRequired
						};
					} else {
						const labels = options.map(item => item.label);
						data = {
							id: id,
							name: name.trim(),
							type: type,
							data: {
								options: labels
							},
							isRequired: isRequired
						};
					}
					if (this.isEdit) {
						this.updateSessionSummary(data);
					} else {
						this.createSessionSummary(data);
					}
				} else {
					console.log('validate error : ', valid);
					return false;
				}
			});
		},
		onRemove(index) {
			this.form.options.splice(index, 1);
			this.changeOptionsValue();
		},
		onAdd() {
			const count = this.form.options.length + 1;
			const data = {
				label: '', // `选项${count}`,
				value: count
			};
			this.form.options.push(data);
			this.changeOptionsValue();
		},
		changeOptionsValue() {
			this.form.options = this.form.options.map((item, index) => {
				return {
					label: item.label,
					value: index + 1
				};
			});
		},
		checkDuplicates(rule, value, callback) {
			const labels = this.form.options.map(item => item.label);
			const duplicates = labels.filter((item, index) => item.trim() === value.trim());
			if (duplicates.length > 1) {
				callback(new Error('输入内容不能有重复!'));
			} else {
				callback();
			}
		},
		createSessionSummary(data) {
			addSessionSummary(this.$route.params.id, data)
				.then(res => {
					console.log('addSessionSummary res', res);
					this.$message({
						message: '添加成功',
						type: 'success'
					});
					this.$emit('save', res.data.data);
				})
				.catch(err => {
					console.log('addSessionSummary err', err);
					this.$message({
						message: '添加失败',
						type: 'error'
					});
				});
		},
		updateSessionSummary(data) {
			updateSessionSummary(this.$route.params.id, this.data.id, data)
				.then(res => {
					console.log('updateSessionSummary res', res);
					this.$message({
						message: '更新成功',
						type: 'success'
					});
					this.$emit('update', {...this.data, ...data});
				})
				.catch(err => {
					console.log('updateSessionSummary err', err);
					this.$message({
						message: '更新失败',
						type: 'error'
					});
				});
		}
	}
};
</script>

<style scoped lang="less">
.summary-create-container {
	.el-input {
		width: 80%;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.minus-button {
		margin-left: 10px;
	}

	.plus-button {
		margin-left: 10px;
	}

	.dialog-footer {
		text-align: center;
	}
}
</style>
